<template>
  <view class="video-list">
    <!-- 遍历 Vuex 中的 videosAbout，根据状态选择不同的组件 -->
    <view v-for="video in videosAbout" :key="video.videoId" class="card-wrapper">
      <FreeCardComponent v-if="video.status === '1'" :video="video" />
      <PayCardComponent v-else-if="video.status === '2'" :video="video" />
      <PurchasedCard v-else-if="video.status === '3'" :video="video" />
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex';
import FreeCardComponent from './free_card.vue'; // 确保路径正确
import PayCardComponent from './pay_card.vue'; // 确保路径正确
import PurchasedCard from './purchased_card.vue'; // 确保路径正确

export default {
  props: {
    triggerUpdate: Boolean, // 增加 triggerUpdate 作为 prop
  },
  components: {
    FreeCardComponent,
    PayCardComponent,
    PurchasedCard,
  },
  computed: {
    // 使用 Vuex 的 state 中的 videosAbout 和 userInfo
    ...mapState(['videosAbout', 'userInfo']),
  },
  watch: {
    triggerUpdate: {
      handler() {
        // 当 triggerUpdate 变化时，调用 updateVideoStatus
        this.updateVideoStatus();
      },
      immediate: true,
    },
  },
  methods: {
    updateVideoStatus() {
      const userInfo = this.userInfo;
      console.log(userInfo.purchased, '用户的购买记录');
      if (userInfo.isVIP) {
        // 如果是 VIP，将所有状态为 '2' 的视频改为 '3'
        const updatedVideos = this.videosAbout.map((video) => {
          if (video.status === '2') {
            video.status = '3';
          }
          return video;
        });
        this.$store.commit('setVideosAbout', updatedVideos);
      } else if (userInfo.purchased && Array.isArray(userInfo.purchased)) {
        // 如果不是 VIP，将 userInfo.purchased 中的视频状态改为 '3'
        const updatedVideos = this.videosAbout.map((video) => {
          if (userInfo.purchased.includes(video.videoId)) {
            video.status = '3';
          }
          return video;
        });
        this.$store.commit('setVideosAbout', updatedVideos);
      }
    },
  },
};
</script>

<style scoped>
.video-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 10px;
  justify-items: center;
}

.card-wrapper {
  width: 100%;
}
</style>
